﻿using AutoMapper;
using ESSManageService.Model.ViewModels;
using ESSManageService.Model;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using ESSManageService.Model.DBModels.Info;
using ESSManageService.IServices.IDBServices;
using Microsoft.Extensions.Logging;
using static System.Runtime.InteropServices.JavaScript.JSType;
using ESSManageService.Enum.ViewEnum;
using System.Drawing.Printing;
using Microsoft.AspNetCore.Authorization;
using System.IdentityModel.Tokens.Jwt;
using ESSManageService.IServices;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Security.Claims;
using ESSManageService.Common.Helper;
using Microsoft.IdentityModel.Tokens;

namespace ESSManageService.API.Controllers
{
    /// <summary>
    /// 用户控制器，提供与用户和角色相关的 API 接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Produces("application/json")]
    [Authorize] // 整个控制器需要认证
    public class UserController : BaseApiController
    {
        private readonly IMapper _mapper;
        private readonly ILogger<UserController> _logger;
        readonly IRoleServices _roleServices;
        readonly IUserInfoServices _userInfoServices;
        private readonly ITokenBlacklistService _tokenBlacklistService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="user"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public UserController(IMapper mapper, ILogger<UserController> logger
            , IRoleServices roleServices, IUserInfoServices userInfoServices
            , ITokenBlacklistService tokenBlacklistService)
        {
            _mapper = mapper;
            _logger = logger;
            _roleServices = roleServices;
            _userInfoServices = userInfoServices;
            _tokenBlacklistService = tokenBlacklistService;
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel<List<Role>> GetAllRoles()
        {
            var data =  _roleServices.GetAllRoles();
            //return SuccessPage(1,data.Count,1,data,10);
            return Success(data, "获取成功");
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="PageSize">每页数</param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "管理员,教练员")]
        public async Task<MessageModel<PageModel<UserInfo>>> GetAllUsers(int page = 1, int PageSize = 50)
        {
            string orderBy = "id desc";
            var data = await _userInfoServices.GetAllUserInfo(orderBy, out int pageCount, out int totalCount, page, PageSize);
            return SuccessPage(page, totalCount, PageSize, data, pageCount);
        }

        [HttpGet("{id}")]
        [AllowAnonymous]
        public string Get(string id)
        {
            _logger.LogError("test wrong");
            return "value";
        }

        // GET: api/User/5
        /// <summary>
        /// 获取用户详情根据token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<UserInfo>> GetInfoByToken()
        {
            var data = new MessageModel<UserInfo>();

            // 获取当前令牌
            var authorizationHeader = HttpContext.Request.Headers["Authorization"].ToString();
            if (string.IsNullOrEmpty(authorizationHeader) || !authorizationHeader.StartsWith("Bearer "))
            {
                _logger.LogWarning("无效的授权头格式");

                data.status = 1002;
                data.msg = "授权头格式应为：Bearer [token]";
                data.data = null;
                return data;
            }
            var token = authorizationHeader.Substring("Bearer ".Length).Trim();
            var tokenModel = _tokenBlacklistService.GetPrincipalFromToken(token);
            string userId = tokenModel?.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            var userinfo = _userInfoServices.GetUserInfo(userId.ObjToLong());
            if (userinfo != null)
            {
                data.data = _mapper.Map<UserInfo>(userinfo);
                data.status = 1000;
                data.msg = "获取成功";
            }

            return data;
        }

        /// <summary>
        /// 添加一个用户
        /// </summary>
        /// <param name="sysUserInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] UserInfo userInfo)
        {
            var data = new MessageModel<string>();

            /*userInfo.uLoginPWD = MD5Helper.MD5Encrypt32(userInfo.uLoginPWD);
            userInfo.uRemark = _user.Name;

            var id = await _userInfoServices.Add(_mapper.Map<UserInfo>(userInfo));

            if (id > 0)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }*/

            return data;
        }

        /// <summary>
        /// 更新用户与角色
        /// </summary>
        /// <param name="sysUserInfo"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] UserInfo userInfo)
        {
            var data = new MessageModel<string>();

            /*var oldUser = await _sysUserInfoServices.QueryById(userInfo.id);
            if (oldUser is not { Id: > 0 })
            {
                return Failed<string>("用户不存在或已被删除");
            }

            try
            {
                if (userInfo.LoginPWD != oldUser.LoginPWD)
                {
                    oldUser.CriticalModifyTime = DateTime.Now;
                }

                _mapper.Map(userInfo, oldUser);

                data.success = await _sysUserInfoServices.Update(oldUser);


                if (data.success)
                {
                    data.msg = "更新成功";
                    data.response = oldUser.Id.ObjToString();
                }
            }
            catch (Exception e)
            {
                _unitOfWorkManage.RollbackTran();
                _logger.LogError(e, e.Message);
            }*/

            return data;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(long id)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                /*var userDetail = await _userInfoServices.QueryById(id);
                userDetail.IsDeleted = true;
                data.success = await _userInfoServices.Update(userDetail);
                if (data.success)
                {
                    data.msg = "删除成功";
                    data.response = userDetail?.Id.ObjToString();
                }*/
            }

            return data;
        }
    }
}
